package com.zkingsoft.services.impl;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zkingsoft.constance.Dictionary;
import com.zkingsoft.constance.SystemConstance;
import com.zkingsoft.dao.ChangesDao;
import com.zkingsoft.dao.ExperienceLevelDao;
import com.zkingsoft.dao.FlowExperienceCoinDao;
import com.zkingsoft.dao.TaskDao;
import com.zkingsoft.dao.UsersDao;
import com.zkingsoft.exception.GlobleException;
import com.zkingsoft.model.Changes;
import com.zkingsoft.model.ExperienceLevel;
import com.zkingsoft.model.FlowExperienceCoin;
import com.zkingsoft.model.Project;
import com.zkingsoft.model.Task;
import com.zkingsoft.model.Users;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.LogUtil;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.services.TaskService;
import com.zkingsoft.thread.SendNoFinishTaskOaMsgsThread;
import com.zkingsoft.thread.SendOaMsgsThread;

/**
 * This field was generated by Zking.software.Codegen.
 * 
 * @date 2016-11-10 16:57
 */
@Service("taskService")
public class TaskServiceImpl implements TaskService {

	@Autowired
	private TaskDao taskDao;

	@Autowired
	private UsersDao usersDao;

	@Autowired
	private ExperienceLevelDao exLevelDao;

	@Autowired
	private FlowExperienceCoinDao flowExperienceCoinDao;

	@Autowired
	private ChangesDao changesDao;

	@Override
	public int add(Task task) {

		return taskDao.insert(task);

	}

	@Override
	@Transactional
	public int modify(Task task) {

		return taskDao.update(task);
	}

	@Override
	public int remove(List<Long> list) {

		return taskDao.deleteByIds(list);

	}

	@Override
	public int removeById(Long id) {

		return taskDao.deleteById(id);

	}

	@Override
	public int removeByModel(Task task) {

		return taskDao.deleteByModel(task);

	}

	@Override
	public List<Task> findInPage(Task task, PaginationVO pageVo) {

		return taskDao.selectInPage(task, pageVo);

	}

	@Override
	public List<Task> findByModel(Task task) {

		return taskDao.selectByModel(task);

	}

	@Override
	public int findTotal(Task task) {

		return taskDao.selectTotalRecord(task);

	}

	@Override
	public Task findById(Long id) {

		return taskDao.selectById(id);

	}

	@Override
	public List<Task> findNoStartOrStart() {

		return taskDao.selectNoStartOrStart();
	}

	@Override
	@Transactional
	public int adds(List<Task> list) {
		// 扣除发布人的金币
		Users users = (Users) WebUtil.getSession().getAttribute(SystemConstance.LOGIN_KEY);// 发布人
		if (!Dictionary.USER_ROLE_ZJL.equals(users.getRole().getName())) {
			int useGoldNum = getTotalGoldNum(list, users);
			users.setAge(users.getAge() - useGoldNum);
			usersDao.update(users);
		}
		return taskDao.inserts(list);
	}

	@Override
	@Transactional
	public List<Long> addsAndReturnId(List<Task> list) {
		// 扣除发布人的金币
		Users users = (Users) WebUtil.getSession().getAttribute(SystemConstance.LOGIN_KEY);// 发布人
		if (!Dictionary.USER_ROLE_ZJL.equals(users.getRole().getName())) {
			int useGoldNum = getTotalGoldNum(list, users);
			users.setAge(users.getAge() - useGoldNum);
			usersDao.update(users);
		}
		List<Long> ids = new ArrayList<>();// 新增数据的主键集合
		for (Task task : list) {
			taskDao.insert(task);
			Long id = task.getId();
			ids.add(id);
		}
		return ids;
	}

	@Override
	@Transactional
	public int modifyOrAdd(Task task) throws CloneNotSupportedException {
		int result = 0;
		int resultUpdate = 0;
		int resultAdd = 0;
		int userHaseTotalGoldNum = 0;
		Users user = (Users) WebUtil.getSession().getAttribute(SystemConstance.LOGIN_KEY);// 发布人
		// 如果是总经理数目不限
		if (!Dictionary.USER_ROLE_ZJL.equals(user.getRole().getName())) {
			userHaseTotalGoldNum = (user.getAge() != null && user.getAge() > 0) ? user.getAge() : 0;
		} else {
			userHaseTotalGoldNum = 99999999;
		}
		List<Task> taskList = new ArrayList<Task>();
		String strUserId = task.getStrUserId();// 指派者字符串
		String[] userIdArry = null;
		boolean flag = false;// 是否包含原有的指派人
		boolean isDel = true;// 是否删除原有的
		if (strUserId != null && strUserId != "") {
			userIdArry = strUserId.split(",");
			Task taskData = taskDao.selectById(task.getId());
			// 判断是否包含原有的指派人
			for (int i = 0; i < userIdArry.length; i++) {
				if (Long.valueOf(userIdArry[i]) == taskData.getUserId()) {
					flag = true;// 包含有
					isDel = false;
					// task.setUserId(Long.valueOf(userIdArry[i]));
				}
			}
			// 循环查看需要新增几条新数据
			for (int i = 0; i < userIdArry.length; i++) {
				if (Long.valueOf(userIdArry[i]) != taskData.getUserId()) {
					Task addTask = new Task();
					addTask = (Task) task.clone();
					addTask.setId(null);// 去掉克隆生成的主键
					addTask.setUserId(Long.parseLong(userIdArry[i]));
					addTask.setCreateUserId(user.getId());
					addTask.setStatus(Dictionary.TASK_STATUS_NO_START);
					addTask.setOvertime(0L);
					addTask.setIsdel(Dictionary.TASK_NO_DEL);
					taskList.add(addTask);

				}
			}
			if (isDel) {
				// guchunxi 删除原来的要退回金币
				Task delTask = taskDao.selectById(task.getId());
				if (delTask.getGoldNum() != null && delTask.getGoldNum() > 0) {
					userHaseTotalGoldNum += delTask.getGoldNum();
				}
				user.setAge(userHaseTotalGoldNum);
				resultUpdate = taskDao.deleteById(task.getId());
			}
			List<Long> taskIds = null;// 新增的任务主键集合
			if (taskList.size() > 0) {
				// guchunxia 添加要扣减用户的金币
				int useTotalGoldNum = getTotalGoldNum(taskList, user);
				userHaseTotalGoldNum -= useTotalGoldNum;
				user.setAge(userHaseTotalGoldNum);
				// resultAdd = taskDao.inserts(taskList);// 添加新增的数据
				taskIds = addsAndReturnId(taskList);
				resultAdd = taskIds.size();
			}
			if (resultAdd > 0) {
				// 发送oa消息
				SendOaMsgsThread send = new SendOaMsgsThread(taskDao, taskIds, Dictionary.BG_COLOR_NO_START,
						Dictionary.TITLE_NO_START, false, null);
				new Thread(send).start();
			}
		}
		if (flag) {
			// guchunxia 先查询出来原来的金币还回去，在扣减现在的金币
			Task delTask = taskDao.selectById(task.getId());
			if (delTask.getGoldNum() != null && delTask.getGoldNum() > 0) {
				userHaseTotalGoldNum += delTask.getGoldNum();
			}
			if (task.getGoldNum() != null && task.getGoldNum() > 0) {
				if (userHaseTotalGoldNum < task.getGoldNum()) {
					throw new GlobleException("您的金币不足！");
				}
				userHaseTotalGoldNum -= task.getGoldNum();
			}
			user.setAge(userHaseTotalGoldNum);

			resultUpdate = taskDao.update(task);
		}
		// 不是总经理就要扣除金币
		if (!Dictionary.USER_ROLE_ZJL.equals(user.getRole().getName())) {
			usersDao.update(user);
		}
		result = resultAdd + resultUpdate;
		return result;

	}

	@Override
	@Transactional
	public Task finishTask(Task task) {
		Task checkTask = taskDao.selectById(task.getId());
		String status = checkTask.getStatus();
		if (!Dictionary.TASK_STATUS_YES_START.equals(status)) {
			throw new GlobleException("状态不是已开始不能修改!");
		}
		// 修改任务的状态
		checkTask.setStatus(Dictionary.TASK_STATUS_FINISHED);
		checkTask.setActEndTime(new Date());
		// 修改这个人完成任务的金币和经验值以及经验等级
		Users taskUser = usersDao.selectById(checkTask.getUserId());
		int goldNum = (checkTask.getGoldNum() != null && !checkTask.getGoldNum().equals("")) ? checkTask.getGoldNum()
				: 0;
		int userGoladNum = (taskUser.getAge() != null && !taskUser.getAge().equals("")) ? taskUser.getAge() : 0;
		// 用户完成任务后当前的金币
		taskUser.setAge(goldNum + userGoladNum);

		if (checkTask.getExperienceNum() != null && !checkTask.getExperienceNum().equals("")) {
			int userExpLevel = (taskUser.getJobTitle() != null && !taskUser.getJobTitle().equals(""))
					? taskUser.getJobTitle() : 0;

			int userExpLevels = (taskUser.getDeptId() != null && !taskUser.getDeptId().equals(""))
					? taskUser.getDeptId() : 0;
			// 用户完成后的总经验
			int exs = userExpLevels + checkTask.getExperienceNum();
			taskUser.setDeptId(exs);
			// 用户完成任务后当前的经验值
			int ex = userExpLevel + checkTask.getExperienceNum();
			// 判断用户当前经验值是否超过当前等级的最大经验值
			ExperienceLevel exLevel = new ExperienceLevel();
			// 判断用户是否有等级,没有则默认为黄铜V
			if (taskUser.getGrade() == null || "".equals(taskUser.getGrade())) {
				taskUser.setGrade(Dictionary.TASL_EXP_LEVEL);
			}
			exLevel.setLevelName(taskUser.getGrade());
			List<ExperienceLevel> exLevelList = exLevelDao.selectByModel(exLevel);
			// 获取所有的等级经验
			List<ExperienceLevel> experienceLevelList = exLevelDao.selectByModel(null);
			String levelName = "";
			// 循环判断用户的经验值是否能够升级,从用户当前等级开始循环
			for (int i = exLevelList.get(0).getLevel() - 1; i < experienceLevelList.size(); i++) {
				// 如果用户的当前经验值大于等于当前等级升级需要的经验值，则升级
				if (ex >= experienceLevelList.get(i).getExperience()) {
					ex = ex - experienceLevelList.get(i).getExperience();
				} else {
					levelName = experienceLevelList.get(i).getLevelName();
					break;
				}
			}
			taskUser.setJobTitle(ex);
			// 用户完成任务后当前的等级
			taskUser.setGrade(levelName);
			// 添加经验金币流水
			FlowExperienceCoin flowExCoin = new FlowExperienceCoin();
			// 经验
			flowExCoin.setExperience(checkTask.getExperienceNum());
			// 金币
			flowExCoin.setCoin(goldNum);
			// 用户id
			flowExCoin.setUserId(checkTask.getUserId());
			// 任务完成时间
			flowExCoin.setTime(new Date());
			flowExperienceCoinDao.insert(flowExCoin);
		}
		int i = taskDao.update(checkTask);
		int j = usersDao.update(taskUser);
		if (i > 0) {
			// 更改问题反馈的状态
			Long changesId = checkTask.getChangesId();
			if (changesId != null) {
				Changes changes = changesDao.selectById(changesId);
				if (changes != null) {
					changes.setHandleResult(Dictionary.DEAL_RESULT_FINISHED);
					changesDao.update(changes);
				}
			}
		}

		if (i > 0 && j > 0) {
			return checkTask;
		}
		return null;
	}

	public String getExpericenLevel(Integer num) {
		String exLevel = Dictionary.TASL_EXP_LEVEL1;
		if (num >= 90) {
			exLevel = Dictionary.TASL_EXP_LEVEL4;
		}
		if (num >= 80) {
			exLevel = Dictionary.TASL_EXP_LEVEL3;
		}
		if (num >= 70) {
			exLevel = Dictionary.TASL_EXP_LEVEL2;
		}
		return exLevel;
	}

	public int getTotalGoldNum(List<Task> list, Users users) {
		int totalGoldNum = 0;
		for (Task obj : list) {
			if (obj.getGoldNum() != null && obj.getGoldNum() > 0) {
				totalGoldNum += obj.getGoldNum();
			}
		}
		Integer userGoldNum = users.getAge();
		if (userGoldNum == null || userGoldNum < totalGoldNum) {
			throw new GlobleException("您的金币余额不足!");
		}
		return totalGoldNum;
	}

	@Override
	@Transactional
	public void taskStatusTimer() {
		List<Task> taskList = taskDao.selectNoStartOrStart();// 状态为未开始和已开始的任务
		if (taskList != null && taskList.size() != 0) {
			Date date = new Date();
			for (Task taskCheckStatus : taskList) {
				Date endTime = taskCheckStatus.getEndTime();
				if (endTime != null) {
					if (date.getTime() > endTime.getTime()) {
						// 当前时间大于预计结束时间 则视为超时，则计算两者相差天天数
						double overTime = (date.getTime() - endTime.getTime()) / (double) (1000 * 60 * 60 * 24);// 想差多少天
						DecimalFormat df = new DecimalFormat("#");// 不保留小数
						df.setRoundingMode(RoundingMode.FLOOR);// 不四舍五入
						taskCheckStatus.setOvertime(Long.parseLong(df.format(overTime)));
						taskDao.update(taskCheckStatus);
					}
				}
			}
		}
	}

	@Override
	public List<Task> findTaskAndDdUserId(String taskIds) {
		return taskDao.selectTaskAndDdUserId(taskIds);
	}

	@Override
	public List<Users> findByIdStr(String idStr) {
		return usersDao.selectByIdStr(idStr);
	}

	@Override
	@Transactional
	public Task cancelTask(Task task) {
		Task checkTask = taskDao.selectById(task.getId());
		String status = checkTask.getStatus();
		// 未开始
		// 已开始
		if (!Dictionary.TASK_STATUS_YES_START.equals(status) && !Dictionary.TASK_STATUS_NO_START.equals(status)) {
			throw new GlobleException("该任务状态为" + status + ",不能取消！");
		}
		// 更新任务
		checkTask.setStatus(Dictionary.TASK_STATUS_CANCEL);
		checkTask.setActEndTime(new Date());
		int result = taskDao.update(checkTask);
		if (result > 0) {
			// 更改问题反馈的状态
			Long changesId = checkTask.getChangesId();
			if (changesId != null) {
				Changes changes = changesDao.selectById(changesId);
				if (changes != null) {
					changes.setHandleResult(Dictionary.DEAL_RESULT_NO);
					changesDao.update(changes);
				}
			}
			return checkTask;
		}
		return null;
	}

	@Override
	@Transactional
	public int delTask(Task task) {
		Task checkTask = taskDao.selectById(task.getId());
		String status = checkTask.getStatus();
		if (!Dictionary.TASK_STATUS_NO_START.equals(status)) {
			throw new GlobleException("只有未开始的任务才可以删除");
		}
		// 设置为已删除
		checkTask.setIsdel(Dictionary.TASK_ISDELY);
		return taskDao.update(checkTask);
	}

	@Override
	public void SendNoFinishedTaskOa() {
		SendNoFinishTaskOaMsgsThread send = new SendNoFinishTaskOaMsgsThread(taskDao, Dictionary.BG_COLOR_NO_FINISHED,
				Dictionary.TITLE_NO_FINISHED);
		new Thread(send).start();
	}

	@Override
	public List<Task> findTaskNoFinish(Long userId) {
		return taskDao.selectTaskNoFinish(userId);
	}

	@Override
	public List<Task> findProjTaskAll(Long projId) {
		return taskDao.selectProjTaskAll(projId);
	}

	@Override
	public List<Task> findProjFinishTask(Long projId) {
		return taskDao.selectProjFinishTask(projId);
	}

	@Override
	public List<Task> findTaskByMonth(Long id, Date beginTime, Date endTime) {
		return taskDao.selectTaskByMonth(id, beginTime, endTime);
	}
	

}
